//
//  YHBullet.cpp
//  ThunderWarriors
//
//  Created by mac on 13-6-22.
//
//

#include "YHBullet.h"
#include "YHGameDefine.h"
#include "YHGameLayerFight.h"

YHBullet::YHBullet()
{
    m_velocityx = 0;
    m_isActive = true;
    m_HP = 1;
    m_velocityy = kPlayBulletSpeed;
}

YHBullet::~ YHBullet()
{
    
}

bool YHBullet::init()
{
    
    return true;
}

void YHBullet::destroy()
{
    CCSprite* sprite = CCSprite::create(s_hit);
    ccBlendFunc cbl = {GL_SRC_ALPHA,GL_ONE};
    sprite->setBlendFunc(cbl);
    sprite->setPosition(this->getPosition());
    sprite->setRotation(CCRANDOM_0_1()*360);
    sprite->setScale(0.75);
    YHGameLayerFight::sharedGameLayerFight()->addChild(sprite,kExplosionZorder);
    
    
    CCCallFuncN* removeSprite = CCCallFuncN::create(this, callfuncN_selector(YHBullet::removeSprite));
    sprite->runAction(CCScaleBy::create(0.3, 2, 2));
    sprite->runAction(CCSequence::create(CCFadeOut::create(0.3), removeSprite, NULL));
    
    this->removeFromParentAndCleanup(true);
}

void YHBullet::hurt()
{
    m_HP --;
    if (m_HP <= 0) {
        m_isActive = false;
    }
}

CCRect YHBullet::getCollideCrect()
{
    CCPoint pos = this->getPosition();
    return CCRectMake(pos.x-3, pos.y-3, 6, 6);
}

void YHBullet::update(float t)
{
    CCPoint pos = this->getPosition();
    pos.x  -= m_velocityx * t;
    pos.y  += m_velocityy * t;
    setPosition(pos);
    if (m_HP <= 0) {
        m_isActive = false;
    }
}

bool YHBullet::initWithBulleName(const char* bulletName, int bulletSpeed)
{
    m_velocityy = bulletSpeed;
    CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile(s_bullet_plist);
    this->initWithSpriteFrameName(bulletName);
    ccBlendFunc cbl = {GL_SRC_ALPHA, GL_ONE};
    this->setBlendFunc(cbl);
    return true;
}


YHBullet* YHBullet::create(const char* bulletName, int bulletSpeed)
{
    YHBullet* pRet = new YHBullet();
    if (pRet && pRet->initWithBulleName(bulletName, bulletSpeed)) {
        pRet->autorelease();
        return pRet;
    }
    if (pRet) delete pRet;
    return NULL;
}

void YHBullet::removeSprite(CCNode* pSender){
    pSender->removeFromParentAndCleanup(true);
}


